const checkUserAgent = require("../util/checkUserAgent");
const Controller = require("egg").Controller

class ResourceController extends Controller {

    //添加资源
    async create() {
        try {
            const body = this.ctx.request.body
            await this.ctx.service.resources.addResources(body)
            this.ctx.body = {
                code: 20000,
                msg: true
            }
        } catch (error) {
            this.ctx.body = {
                code: 50000,
                message: false
            }
        }
    }
    //获取资源
    async index() {
        try {
            const query = this.ctx.request.query
            const videoList = await this.ctx.service.resources.getResources(query)
            this.ctx.body = {
                code: 20000,
                message: true,
                data: videoList
            }
        } catch (error) {
            this.ctx.body = {
                code: 50000,
                message: false
            }
        }
    }
    //删除资源
    async destroy() {
        try {
            const id = this.ctx.params.id
            await this.ctx.service.resources.deleteResources(id)
            this.ctx.body = {
                code: 20000,
                message: true
            }
        } catch (error) {
            this.ctx.body = {
                code: 50000,
                message: false
            }
        }
    }
    //更新资源
    async update() {
        try {
            const id = this.ctx.params.id
            const body = this.ctx.request.body
            await this.ctx.service.resources.updateResources(id, body)
            this.ctx.body = {
                code: 20000,
                message: true
            }
        } catch (error) {
            this.ctx.body = {
                code: 50000,
                message: false
            }
        }
    }
    async getResourceList() {
        const { ctx } = this;
        const ua = checkUserAgent(ctx.header['user-agent'])
        const data = await ctx.service.website.getResourceList()
        if (ua) {
            await ctx.render("pc/resource.html", data )
        } else {
            await ctx.render("mobile/resource.html", data )
        }
    }
}

module.exports = ResourceController